<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商户名称" prop="shopName">
        <el-input v-model="queryParams.shopName" placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商户id" prop="shopId">
        <el-input v-model="queryParams.shopId" placeholder="请输入商户id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="开始时间" prop="start">
        <el-date-picker clearable v-model="queryParams.start" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="end">
        <el-date-picker clearable v-model="queryParams.end" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="收款金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="请输入收款金额" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收据地址" prop="sign">
        <el-input v-model="queryParams.sign" placeholder="请输入收据地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建者" prop="creator">
        <el-input v-model="queryParams.creator" placeholder="请输入创建者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收款日期" prop="receivePaymentDate">
        <el-date-picker clearable v-model="queryParams.receivePaymentDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择收款日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['admin:settlement:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['admin:settlement:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['admin:settlement:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['admin:settlement:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="settlementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" width="80" />
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <el-table-column label="商户名称" align="center" prop="shopName" />
      <!-- <el-table-column label="商户id" align="center" prop="shopId" /> -->
      <el-table-column label="开始时间" align="center" prop="start" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.start, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="end" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.end, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收款类型" align="center" prop="type" />
      <el-table-column label="收款金额" align="center" prop="amount" />
      <el-table-column label="收据地址" align="center" prop="sign" />
      <el-table-column label="创建者" align="center" prop="creator" />
      <el-table-column label="是否收款" align="center" prop="isReceivePayment">
        <template slot-scope="scope">
          <span v-if="scope.row.isReceivePayment == 0">未收款</span>
          <span v-if="scope.row.isReceivePayment == 1">已收款</span>
          <!-- <span v-if="scope.row.isReceivePayment == 2">收款中</span> -->
        </template>
      </el-table-column>
      <el-table-column label="收款日期" align="center" prop="receivePaymentDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receivePaymentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否删除" align="center" prop="isDel">
        <template slot-scope="scope">
          <span v-if="scope.row.isDel == 0">未删除</span>
          <span v-if="scope.row.isDel == 1">已删除</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:settlement:edit']">查看详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateReceivePayment(scope.row)"
            v-hasPermi="['admin:settlement:edit']">修改收款状态</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['admin:settlement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改结算单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyId">
              <el-select v-model="form.companyId" filterable @change="handleCompanyChange" placeholder="请选择所属公司"
                v-if="isAdmin && title !== '修改结算单'">
                <el-option v-for="item in topUserList" :key="item.id" :label="item.nickname" :value="item.id" />
              </el-select>
              <!-- <el-input v-model="form.companyName" placeholder="请输入公司名称"  v-else-if="title !== '修改结算单'" /> -->
              <el-input v-model="form.companyName" placeholder="请输入公司名称" disabled v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户名称" prop="shopId">
              <el-select v-model="form.shopId" placeholder="请选择商户" filterable clearable @change="handleShopChange"
                v-if="title !== '修改结算单'">
                <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
              </el-select>
              <el-input v-model="form.shopName" placeholder="请输入商户名称" disabled v-else />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建者" prop="creator">
              <el-select v-model="form.creator" placeholder="请选择创建者" filterable clearable v-if="title !== '修改结算单'">
                <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
              </el-select>
              <el-input v-model="form.creator" placeholder="请输入创建者" disabled v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择收款类型" filterable clearable v-if="title !== '修改结算单'">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-input v-model="form.type" placeholder="请输入收款类型" disabled v-else />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="start">
              <el-date-picker clearable v-model="form.start" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始时间"
                @change="(val) => handleDateChange(val, 'start')" v-if="title !== '修改结算单'">
              </el-date-picker>
              <el-input v-model="form.start" placeholder="请输入开始时间" disabled v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="end">
              <el-date-picker clearable v-model="form.end" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间"
                @change="(val) => handleDateChange(val, 'end')" v-if="title !== '修改结算单'">
              </el-date-picker>
              <el-input v-model="form.end" placeholder="请输入结束时间" disabled v-else />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="商户id" prop="shopId">
          <el-input v-model="form.shopId" placeholder="请输入商户id" />
        </el-form-item> -->

        <el-form-item label="订单列表" prop="orderList">
          <el-table :data="orderList" border>
            <!-- <el-table-column label="订单id" align="center" prop="id" /> -->
            <el-table-column label="商户名称" align="center" prop="merchantName" />
            <el-table-column label="订单日期" align="center" prop="date" />
            <el-table-column label="订单金额" align="center" prop="amount" />
            <!-- <el-table-column label="订单状态" align="center" prop="status" /> -->
            <!-- <el-table-column label="订单备注" align="center" prop="remark" /> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleOrderDetail(scope.row)"
                  v-hasPermi="['admin:settlement:edit']">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="应收金额" prop="amount">
          <el-input v-model="form.amount" placeholder="" disabled />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title !== '修改结算单'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="shopDetailTitle" :visible.sync="shopDetailOpen" width="800px" append-to-body>
      <el-table :data="shopDetailList" border>
        <el-table-column label="商品名称" align="center" prop="shopName" />
        <el-table-column label="商品规格" align="center" prop="shopSpec" />
        <el-table-column label="商品数量" align="center" prop="shopNumber" />
        <el-table-column label="商品单价" align="center" prop="shopPrice" />
        <el-table-column label="商品金额" align="center" prop="shopAmount" />
      </el-table>
    </el-dialog>
    <el-dialog :title="receivePaymentTitle" :visible.sync="ReceivePaymentOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收款日期" prop="receivePaymentDate">
          <el-date-picker clearable v-model="form.receivePaymentDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收款凭证" prop="sign">
          <el-upload action="http://localhost:8080/admin/user/upload"
            :class="{ 'hide': form.sign != null && form.sign != '' }" list-type="picture-card"
            :limit="1" :on-progress="(event, file) => handleProgress(event, file, 'sign')"
            :on-preview="(file) => handlePictureCardPreview(file, 'sign')"
            :on-success="(res, file) => handleAvatarSuccess(res, file, 'sign')"
            :on-remove="(file, fileList) => handleRemove(file, fileList, 'sign')">
            <img v-if="form.sign" :src="form.sign" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReceivePaymentForm">确 定</el-button>
        <el-button @click="cancelReceivePayment">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex"
import { listShop } from "@/api/admin/shop"
import { listUser } from "@/api/admin/user"
import { listOrder } from "@/api/admin/order"
import { listSettlement, getSettlement, delSettlement, addSettlement, updateSettlement } from "@/api/admin/settlement"

import add from "./add"
import uploadMixin from '@/utils/upload'
import { handlePictureCardPreview, handleRemove, handleAvatarSuccess, handleProgress } from '@/utils/upload'

export default {
  name: "Settlement",
  mixins: [add, uploadMixin],
  computed: {
    ...mapGetters(["roles", "nickname", "bindUserId", "topUserList"]),
    isAdmin() {
      return this.roles.includes("admin")
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 结算单表格数据
      settlementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopName: null,
        shopId: null,
        start: null,
        end: null,
        isReceivePayment: null,
        amount: null,
        sign: null,
        isDel: null,
        creator: null,
        type: null,
        receivePaymentDate: null,
        companyId: null,
        companyName: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      shopList: [],
      userList: [],
      orderList: [],
      shopDetailList: [],
      shopDetailOpen: false,
      shopDetailTitle: '',
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询结算单列表 */
    async getList() {
      this.loading = true
      // const res = await listUser({
      //   top: this.bindUserId,
      //   type: 1,
      // })
      // this.userList = res.rows
      console.log("this.userList==>", this.topUserList)
      listSettlement(this.queryParams).then(response => {
        this.settlementList = response.rows
        this.settlementList.forEach((item, i) => {
          this.topUserList.forEach(it => {
            if (item.companyId == it.id) {
              this.$set(this.settlementList[i], 'companyName', it.nickname)
            }
          });
        });
        console.log("this.settlementList==>", this.settlementList)
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopName: null,
        shopId: null,
        start: null,
        end: null,
        isReceivePayment: null,
        orderIds: [],
        amount: null,
        sign: null,
        isDel: null,
        creator: null,
        type: null,
        receivePaymentDate: null,
        createTime: null,
        updateTime: null,

      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加结算单"
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      const res = await getSettlement(id)
      this.form = res.data
      this.open = true
      this.title = "修改结算单"
      this.getOrderList({
        companyId: this.form.companyId,
        merchantId: this.form.shopId,
        isSettlement: 2,
        type: 1,
        start: this.form.start,
        end: this.form.end,
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSettlement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            this.form.orderIds = this.orderList.map(item => item.id)
            console.log("this.form.orderIds==>", this.form.orderIds)
            addSettlement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除结算单编号为"' + ids + '"的数据项？').then(function () {
        return delSettlement(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/settlement/export', {
        ...this.queryParams
      }, `settlement_${new Date().getTime()}.xlsx`)
    },
    getShopList(id) {
      listShop({
        companyId: id,
      }).then(response => {
        this.$nextTick(() => {
          this.shopList = response.rows
        })
        // this.shopList = response.rows
      })
    },
    getUserList(id) {
      listUser({
        top: id,
        type: 1,
      }).then(response => {
        this.userList = response.rows
      })
    },
    handleCompanyChange(val) {
      // this.queryParams.companyId = val
      this.getShopList(val)
      this.getUserList(val)
    },
    handleShopChange(val) {
      // this.form.shopId = val
      console.log("val==>", val)
      this.$set(this.form, 'shopName', this.shopList.find(item => item.id == val).shopName)
      if (this.form.companyId != null && this.form.shopId != null && this.form.end != null && this.form.start != null) {
        this.getOrderList({
          companyId: this.form.companyId,
          merchantId: this.form.shopId,
          isSettlement: 0,
          type: 1,
          start: this.form.start,
          end: this.form.end,
        })
      }
      console.log("this.form==>", this.form)
    },
    getOrderList(form) {
      listOrder(form).then(response => {
        if (response.rows.length > 0) {
          this.orderList = response.rows

          this.orderList.forEach((item, index) => {
            let total = 0
            item.detailList.forEach(detail => {
              // detailList.push(detail)
              total += detail.shopAmount
            })
            this.$set(this.orderList[index], 'amount', total)
          })
          console.log("detailList==>", this.orderList)
          let total = 0
          this.orderList.forEach(item => {
            total += item.amount
          })
          this.$set(this.form, 'amount', total)
        } else {
          this.$modal.msgError("所选时间范围内没有订单数据")
        }
      })
    },
    handleDateChange(val, type) {
      let i;
      if (type == 'start') {
        i = this.form.end
        if (val > i) {
          this.$set(this.form, 'end', val)
          this.$set(this.form, 'start', i)
        } else {
          this.$set(this.form, 'start', val)
        }
      } else if (type == 'end') {
        i = this.form.start
        if (val < this.form.start) {
          this.$set(this.form, 'start', val)
          this.$set(this.form, 'end', i)
        } else {
          this.$set(this.form, 'end', val)
        }
      }
      console.log("this.form==>", this.form)
      if (this.form.companyId != null && this.form.shopId != null && this.form.end != null && this.form.start != null) {
        this.getOrderList({
          companyId: this.form.companyId,
          merchantId: this.form.shopId,
          isSettlement: 0,
          type: 1,
          start: this.form.start,
          end: this.form.end,
        })
      }
      // if(type == 'receivePaymentDate'){
    },
    handleOrderDetail(row) {
      this.shopDetailList = row.detailList
      this.shopDetailOpen = true
      this.shopDetailTitle = '订单详情'
      // console.log("row==>", row)
    }
  }
}
</script>
